var express = require("express");
var router = express.Router();
var fs = require("fs");
const Result = require("../utils/result");
const multer = require("multer");
const userService = require("../services/userService");
const { generateToken } = require("../utils/jwt");
const postService = require("../services/postServices");
const fansService = require("../services/fansService");

const upload = multer({ dest: "public/images/" }); // 文件储存路径
// 检查是否登录
router.get("/check", async function (req, res) {
  const token = req.headers.token;
  res.json(Result.success({ isLogin: token }));
});
// 登录
router.get("/login", async function (req, res) {
  const user = await userService.login(req.query.js_code);
  // 未注册
  if (user.isRegister) {
    res.json(Result.success({ needRegister: true }));
  } else {
    const token = generateToken(user);
    res.json(Result.success({ user, token }));
  }
});
// 注册
router.post("/register", async function (req, res) {
  const body = req.body;
  const user = await userService.register(body);
  const token = generateToken(user);
  res.json(Result.success({ user, token }));
});

// 上传头像
router.post("/upload", upload.single("file"), function (req, res, next) {
  try {
    let file = req.file;
    const oldPath = file.destination + file.filename;
    const type = file.mimetype.split("/")[1];
    const fileFullname = file.filename + "." + type;
    const newPath = "public/images/" + fileFullname;
    // 修改文件名，为文件加上后缀
    fs.rename(oldPath, newPath, function (err) {
      if (err) {
        throw err;
      }
    });
    // 返回静态资源地址
    const imageUrl = "http://localhost:8080/images/" + fileFullname;
    res.json(Result.success({ imageUrl }));
  } catch (error) {
    res.json(Result.fail(error));
  }
});

// 修改用户信息
router.post("/update", async function (req, res) {
  const userData = req.body.userData;
  const user = await userService.modify(userData);
  res.json(Result.success({ user }));
});

//获取用户信息
router.get("/center", async function (req, res) {
  const { userId, currentId, page, size } = req.query;
  //获取用户个人信息
  const info = await userService.getInfo(userId);
  //获取个人动态文章信息
  const { dynamicArr, dynamicCount } = await postService.getAllDynamic(
    userId,
    size,
    page
  );
  //获取当前用户是否关注该中心的用户
  const isConcern = await fansService.isConcern(currentId, userId);
  res.json(Result.success({ info, dynamicArr, dynamicCount, isConcern }));
});

//关注
router.get("/follow", async function (req, res) {
  const { noticerId, followerId } = req.query;
  await fansService.follow(noticerId, followerId);
  res.json(Result.success());
});

//取消关注
router.get("/unfollow", async function (req, res) {
  const { noticerId, followerId } = req.query;
  await fansService.unfollow(noticerId, followerId);
  res.json(Result.success());
});

//获取排行榜数据
router.get("/rank", async function (req, res) {
  const college = req.query.college;
  const { scoreRank, scoreCollegeRank } = await userService.getRank(college);
  res.json(Result.success({ scoreRank, scoreCollegeRank }));
});

//获取个人积分排行
router.get("/myRank", async function (req, res) {
  const { score } = req.query;
  const myRank = await userService.getMyRank(score);
  res.json(Result.success({ myRank }));
});

//获取个人积分同校排行
router.get("/myRankCollege", async function (req, res) {
  const { score, college } = req.query;
  const myRank = await userService.getMyRankCollege(score, college);
  res.json(Result.success({ myRank }));
});

module.exports = router;
